package com.ceshi.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ceshi.dao.ProductDao;
import com.ceshi.dao.TransDao;
import com.ceshi.meta.Product;
import com.ceshi.meta.Trans;

@Controller
public class IndexAction {
	@RequestMapping(value = { "/", "", "index" }, method = RequestMethod.GET)
	public String index(HttpServletRequest req, ModelMap map) {

		// start session
		HttpSession session = req.getSession();
		String usertype = null;
		int userid = -1;
		boolean isLogin = false;

		if (session.getAttribute("username") != null) {
			usertype = (String) session.getAttribute("usertype");
			userid = (Integer) session.getAttribute("userid");
			isLogin = true;
		}

		ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");

		ProductDao productDao = context.getBean(ProductDao.class);
		TransDao transDao = context.getBean(TransDao.class);

		List<Map> products = new ArrayList<Map>();

		List<Product> productList = productDao.getAllproduct();
		for (Product product : productList) {
			System.out.println(product.getId() + "|" + product.getTitle());
			Map haha1 = new HashMap();
			haha1.put("id", product.getId());
			haha1.put("image", product.getIcon());
			haha1.put("title", product.getTitle());
			haha1.put("price", product.getPrice());
			boolean isBuy = false;
			boolean isSell = false;

			if (isLogin) {
				// 0 买家，1卖家
				if (usertype.equals("0")) {
					Trans tran = transDao.getTransbyContentIdAndUserid(product.getId(), userid);
					if (tran != null) {
						isBuy = true;
					}
				} else if (usertype.equals("1")) {
					List<Trans> trans = transDao.getTransbyContentId(product.getId());
					if (trans.size() > 0) {
						isSell = true;
					}
				}

			}

			haha1.put("isBuy", isBuy);
			haha1.put("isSell", isSell);

			products.add(haha1);
		}

		map.addAttribute("productList", products);

		return "index";
	}

}